package es;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.Map;

public class EsRestClient {

    private String ip;
    private int port;
    private String index;
    RestHighLevelClient client;

    @Before
    public void init() {
        this.ip = "192.168.6.207";
        this.port = 30966;
        this.index = "similar_custom";
        client = new RestHighLevelClient(RestClient.builder(new HttpHost(ip, port, "http")));
    }


    public void search(QueryBuilder queryBuilder, int size, String indice) throws IOException {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(queryBuilder).from(0).size(size).trackTotalHits(false);
        SearchRequest searchRequest = new SearchRequest().indices(indice).source(searchSourceBuilder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchHits = response.getHits();
        for (SearchHit hit : searchHits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            System.out.println(sourceAsMap.get("share"));
            if (null == sourceAsMap.get("orgid")){
                System.out.println("0000000000000");
            }
            String a = String.valueOf(sourceAsMap.get("orgid"));
            System.out.println("----------->" + (a.equals("null")));
            System.out.println(String.valueOf(sourceAsMap.get("orgid")));
        }
        System.out.println(searchHits.getHits().length);
        System.out.println("end");
//        return SearchHandler.handle(response);
    }


    @Test
    public void test1() throws IOException {
        BoolQueryBuilder customBoolQuery = QueryBuilders.boolQuery();
        customBoolQuery.should(QueryBuilders.termQuery("userId", "255945201"));
//        customBoolQuery.should(QueryBuilders.termsQuery("orgid", task.getOrgIds()));
        search(customBoolQuery, 10, index);
    }
}
